package com.ljl;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author 刘家良
 * @date 2022/10/26 00:36
 * @description
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        int port = 7035;
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //定义两个EventLoopGroup
        NioEventLoopGroup bossLoop = new NioEventLoopGroup(1);
        NioEventLoopGroup workerLoop = new NioEventLoopGroup();
        ChannelFuture sync = serverBootstrap.group(bossLoop, workerLoop)
                //保持连接
                .option(ChannelOption.SO_KEEPALIVE, true)
                .channel(NioServerSocketChannel.class)
                //客户端通道连接时，初始化方法
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringDecoder(Charset.forName("gbk")));
                        pipeline.addLast(new StringEncoder(Charset.forName("gbk")));
                        pipeline.addLast(new MsgHandler());
                    }
                })
                //侦听端口
                .bind(port).sync();
        System.out.println("开始监听端口：" + port);
        //等待客户端的断开
        sync.channel().closeFuture().sync();

        //资源清理
        workerLoop.shutdownGracefully();
        bossLoop.shutdownGracefully();
    }

}
